package com.wosai.teach.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.wosai.teach.R;
import com.wosai.teach.adapter.SimulationContentAdapter;
import com.wosai.teach.adapter.SimulationTitleAdapter;
import com.wosai.teach.cst.C;
import com.wosai.teach.dialog.NewProgressDialog;
import com.wosai.teach.dto.JsonResult;
import com.wosai.teach.entity.ExpType;
import com.wosai.teach.entity.Experiment;
import com.wosai.teach.entity.GridInfo;
import com.wosai.teach.utils.OtherUtils;

@ContentView(R.layout.activity_simulation)
public class SimulationActivity extends AppActivity {
	@ViewInject(R.id.gv_simu_title)
	private GridView titleGrid;
	@ViewInject(R.id.gv_simu_content)
	private GridView contentGrid;

	private String className;

	private String type = "0";

	private NewProgressDialog progressdialog;

	private SimulationTitleAdapter titleAdapter;

	private SimulationContentAdapter contentAdapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		enableBack(true);
		setTopTitle("中策仿真");
		className = this.getClass().toString();
		Intent it = getIntent();
		type = it.getStringExtra("type");
		type = type == null ? "0" : type;

		System.out.println("SimulationActivity||type||" + type);
		initView();

		// 调用接口
		if ("0".equals(type)) {
			callFace();
		} else {
			callFaceAllType();
			callFaceByType(type);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	public void initView() {
		titleAdapter = new SimulationTitleAdapter(this,
				new ArrayList<GridInfo>());
		titleGrid.setAdapter(titleAdapter);

		contentAdapter = new SimulationContentAdapter(this,
				new ArrayList<GridInfo>());
		contentGrid.setAdapter(contentAdapter);

		final Activity self = this;
		contentGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				System.out.println(position);
				GridInfo grid = (GridInfo) parent.getAdapter()
						.getItem(position);
				Intent it = new Intent(self, ExpDetailAction.class);
				it.putExtra("expId", grid.getRelId());
				self.startActivity(it);
			}
		});

		titleGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				GridInfo gridInfo = (GridInfo) parent.getAdapter().getItem(
						position);

				callFaceByType(gridInfo.getOtherDesc());
			}
		});
	}

	/**
	 * 请求所有数据
	 */
	public void callFace() {
		progressdialog = NewProgressDialog
				.showProgress(this, "努力加载中...", false);
		String url = C.HTTP_URL_EXPERIMENT_LIST;
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							JSONObject jsonObject = JSON.parseObject(result
									.getObject().toString());
							List<Experiment> expList = JSON.parseArray(
									jsonObject.getString("experimentList"),
									Experiment.class);
							db.deleteAll(Selector.from(GridInfo.class)
									.where("className", "=", className)
									.and("sequence", "=", 1));
							db.deleteAll(Selector.from(Experiment.class));
							db.saveAll(expList);
							for (Experiment exp : expList) {
								GridInfo grid = new GridInfo();
								grid.setClassName(className);
								grid.setSequence(1);
								grid.setName(exp.getExpName());
								grid.setImage(exp.getPicURL1());
								grid.setRelId(exp.getExpId() + "");
								grid.setType("0");
								grid.setOtherDesc(exp.getHotCount());
								db.save(grid);
							}

							db.deleteAll(Selector.from(ExpType.class));
							db.deleteAll(Selector.from(GridInfo.class)
									.where("className", "=", className)
									.and("sequence", "=", 0));
							List<ExpType> typeList = JSON.parseArray(
									jsonObject.getString("expTypeList"),
									ExpType.class);
							db.saveAll(typeList);
							for (ExpType type : typeList) {
								GridInfo grid = new GridInfo();
								grid.setClassName(className);
								grid.setSequence(0);
								grid.setOtherDesc(type.getId() + "");
								grid.setName(type.getName());
								db.save(grid);
							}
							callResult(true);
							callResult2("0", true);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						callResult(false);
						callResult2("0", false);
					}
				});
	}

	/**
	 * 获取实验分类
	 */
	public void callFaceAllType() {
		String url = C.HTTP_URL_EXPERIMENT_TYPE;
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							List<ExpType> typeList = JSON.parseArray(result
									.getObject().toString(), ExpType.class);
							db.deleteAll(Selector.from(ExpType.class));
							db.deleteAll(Selector.from(GridInfo.class)
									.where("className", "=", className)
									.and("sequence", "=", 0));
							db.saveAll(typeList);
							for (ExpType type : typeList) {
								GridInfo grid = new GridInfo();
								grid.setClassName(className);
								grid.setSequence(0);
								grid.setOtherDesc(type.getId() + "");
								grid.setName(type.getName());
								db.save(grid);
							}
							callResult(true);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						callResult(false);
					}
				});

	}

	/**
	 * 获取实验下的分类
	 * 
	 * @param type
	 */
	public void callFaceByType(final String type) {
		progressdialog = NewProgressDialog
				.showProgress(this, "努力加载中...", false);
		String url = C.HTTP_URL_EXPERIMENT_LIST_BY_TYPE;
		url = url.replace("{type}", type);
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
						System.out.println("onSuccess" + responseInfo.result);
						JsonResult result = OtherUtils
								.genJsonResult(responseInfo);
						if (result != null && result.getResult() == 0) {
							List<Experiment> expList = JSON.parseArray(result
									.getObject().toString(), Experiment.class);
							db.deleteAll(Selector.from(GridInfo.class)
									.where("className", "=", className)
									.and("sequence", "=", 1)
									.and("type", "=", type));
							db.deleteAll(Selector.from(Experiment.class));
							db.saveAll(expList);
							for (Experiment exp : expList) {
								GridInfo grid = new GridInfo();
								grid.setClassName(className);
								grid.setSequence(1);
								grid.setName(exp.getExpName());
								grid.setImage(exp.getPicURL1());
								grid.setRelId(exp.getExpId() + "");
								grid.setType(type);
								grid.setOtherDesc(exp.getHotCount());
								db.save(grid);
							}
							callResult2(type, true);
						}
					}

					@Override
					public void onFailure(HttpException error, String msg) {
						System.out.println("onFailure" + msg);
						callResult2(type, false);
					}
				});
	}

	/**
	 * 接口结束
	 */
	public void callResult(boolean success) {
		List<GridInfo> girdList = new ArrayList<GridInfo>();
		girdList = db.findAll(Selector.from(GridInfo.class)
				.where("className", "=", className).and("sequence", "=", 0));
		if (OtherUtils.CheckNull(girdList)) {
			// 没有数据
			if (success) {
				titleAdapter.setObjList(new ArrayList<GridInfo>());
			}
		} else {
			titleAdapter.setObjList(girdList);
		}
		titleAdapter.notifyDataSetChanged();
	}

	public void callResult2(String type, boolean success) {
		List<GridInfo> girdList = new ArrayList<GridInfo>();
		if (type.equals("0")) {
			girdList = db
					.findAll(Selector.from(GridInfo.class)
							.where("className", "=", className)
							.and("sequence", "=", 1));
		} else {
			girdList = db.findAll(Selector.from(GridInfo.class)
					.where("className", "=", className).and("sequence", "=", 1)
					.and("type", "=", type));
		}

		if (OtherUtils.CheckNull(girdList)) {
			// 没有数据
			if (success) {
				contentAdapter.setObjList(new ArrayList<GridInfo>());
			}
		} else {
			contentAdapter.setObjList(girdList);
		}
		contentAdapter.notifyDataSetChanged();
		if (progressdialog != null) {
			progressdialog.dismiss();
		}

		for (int i = 0; i < titleGrid.getChildCount(); i++) {
			View v = titleGrid.getChildAt(i);
			if ((i + 1) == Integer.parseInt(type)) {
				v.setBackgroundColor(Color.parseColor("#0A000000"));
			} else {
				v.setBackgroundColor(Color.WHITE);
			}
		}

	}
}
